//
//  IFlySpeechRecognizerExample.swift
//  GLUZSwift
//
//  Created by AI Assistant on 2024/12/19.
//  Copyright © 2024 考拉🐨. All rights reserved.
//

import UIKit

// MARK: - 语音识别使用示例
class IFlySpeechRecognizerExample: UIViewController {
    
    // MARK: - UI元素
    @IBOutlet weak var resultLabel: UILabel!
    @IBOutlet weak var startButton: UIButton!
    @IBOutlet weak var stopButton: UIButton!
    @IBOutlet weak var cancelButton: UIButton!
    @IBOutlet weak var languageSegmentedControl: UISegmentedControl!
    @IBOutlet weak var statusLabel: UILabel!
    
    // MARK: - 属性
    private var currentResult = ""
    
    // MARK: - 生命周期
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        setupSpeechRecognizer()
    }
    
    // MARK: - 私有方法
    private func setupUI() {
        title = "语音识别示例"
        
        // 设置按钮状态
        updateButtonStates()
        
        // 设置语言选择器
        languageSegmentedControl.setTitle("中文", forSegmentAt: 0)
        languageSegmentedControl.setTitle("俄文", forSegmentAt: 1)
        languageSegmentedControl.selectedSegmentIndex = 0
        
        // 设置初始状态
        statusLabel.text = "准备就绪"
        resultLabel.text = "识别结果将显示在这里..."
    }
    
    private func setupSpeechRecognizer() {
        // 设置代理
        IFlySpeechRecognizerManager.shared.delegate = self
        
        // 设置初始语言
        IFlySpeechRecognizerManager.shared.setLanguage(.chinese)
    }
    
    private func updateButtonStates() {
        let isListening = IFlySpeechRecognizerManager.shared.isListening
        
        startButton.isEnabled = !isListening
        stopButton.isEnabled = isListening
        cancelButton.isEnabled = isListening
        
        startButton.alpha = isListening ? 0.5 : 1.0
        stopButton.alpha = isListening ? 1.0 : 0.5
        cancelButton.alpha = isListening ? 1.0 : 0.5
    }
    
    // MARK: - 按钮事件
    @IBAction func startButtonTapped(_ sender: UIButton) {
        // 清空之前的结果
        currentResult = ""
        resultLabel.text = "正在识别..."
        
        // 开始识别
        let success = IFlySpeechRecognizerManager.shared.startListening()
        if success {
            statusLabel.text = "正在识别中..."
            updateButtonStates()
        } else {
            statusLabel.text = "开始识别失败"
        }
    }
    
    @IBAction func stopButtonTapped(_ sender: UIButton) {
        IFlySpeechRecognizerManager.shared.stopListening()
        statusLabel.text = "正在处理结果..."
    }
    
    @IBAction func cancelButtonTapped(_ sender: UIButton) {
        IFlySpeechRecognizerManager.shared.cancelListening()
        statusLabel.text = "已取消识别"
        resultLabel.text = "识别已取消"
        updateButtonStates()
    }
    
    @IBAction func languageChanged(_ sender: UISegmentedControl) {
        let language: IFlySpeechLanguage = sender.selectedSegmentIndex == 0 ? .chinese : .russian
        IFlySpeechRecognizerManager.shared.setLanguage(language)
        statusLabel.text = "已切换到\(language.displayName)"
    }
}

// MARK: - IFlySpeechRecognizerDelegate
extension IFlySpeechRecognizerExample: MyIFlySpeechRecognizerDelegate {
    
    func speechRecognizerDidReceiveResult(_ result: String, isLast: Bool) {
        // 累积识别结果
        currentResult += result
        
        // 更新UI
        DispatchQueue.main.async { [weak self] in
            self?.resultLabel.text = self?.currentResult
        }
        
        print("收到识别结果: \(result), 是否最后结果: \(isLast)")
    }
    
    func speechRecognizerDidComplete(_ error: Error?) {
        DispatchQueue.main.async { [weak self] in
            if let error = error {
                self?.statusLabel.text = "识别失败: \(error.localizedDescription)"
                self?.resultLabel.text = "识别失败"
            } else {
                self?.statusLabel.text = "识别完成"
            }
            self?.updateButtonStates()
        }
    }
    
    func speechRecognizerDidBeginRecording() {
        DispatchQueue.main.async { [weak self] in
            self?.statusLabel.text = "正在录音..."
        }
    }
    
    func speechRecognizerDidEndRecording() {
        DispatchQueue.main.async { [weak self] in
            self?.statusLabel.text = "录音结束，正在识别..."
        }
    }
    
    func speechRecognizerDidChangeVolume(_ volume: Int) {
        DispatchQueue.main.async { [weak self] in
            self?.statusLabel.text = "正在录音... 音量: \(volume)"
        }
    }
    
    func speechRecognizerDidCancel() {
        DispatchQueue.main.async { [weak self] in
            self?.statusLabel.text = "已取消识别"
            self?.resultLabel.text = "识别已取消"
            self?.updateButtonStates()
        }
    }
}

// MARK: - 简单使用示例
extension IFlySpeechRecognizerExample {
    
    /// 简单的语音识别使用示例
    func simpleUsageExample() {
        // 1. 设置代理
        IFlySpeechRecognizerManager.shared.delegate = self
        
        // 2. 设置语言
        IFlySpeechRecognizerManager.shared.setLanguage(.chinese)
        
        // 3. 开始识别
        IFlySpeechRecognizerManager.shared.startListening()
        
        // 4. 停止识别（通常在用户停止说话后自动停止，或手动调用）
        // IFlySpeechRecognizerManager.shared.stopListening()
        
        // 5. 取消识别（如果需要）
        // IFlySpeechRecognizerManager.shared.cancelListening()
    }
}
